#include "itemdialog.h"
#include "ui_itemdialog.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>

ItemDialog::ItemDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemDialog)
{
    ui->setupUi(this);

    this->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
    this->setWindowFlag(Qt::WindowMinimizeButtonHint, false);
}

ItemDialog::~ItemDialog()
{
    delete ui;
}

void ItemDialog::on_add_btn_clicked()
{
    QString item = this->ui->item_lineedit->text();
    QString init_score = this->ui->init_score_spinbox->text();
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "item");
    db.setDatabaseName("data.db");
    if (!db.open()) {
        QMessageBox::critical(this, "系统错误", "无法打开数据库");
        return;
    }
    db.exec("INSERT INTO `item`(`name`, `init_score`) VALUES('" + item + "', " + init_score + ")");
    QSqlError err = db.lastError();
    if (err.isValid()) {
        QMessageBox::critical(this, "系统错误", QString("无法插入数据：") + err.databaseText());
        return;
    }
    db.close();
    QSqlDatabase::removeDatabase("item");
    this->close();
}

